<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      <e-heading>课程表</e-heading>
      <el-form class="form-search">
        <el-row>
          <el-col :span="6">
            <el-date-picker
              size="small"
              v-model="theday"
              type="week"
              format="yyyy 年 MM 月 第 ww 周"
              placeholder="选择周"
              @change="handleChange">
            </el-date-picker>
          </el-col>

          <el-col :span="5" :offset="1">
            <el-select size="small" v-model="address" clearable placeholder="请选择省市">
              <el-option
                v-if='train_compus_selection'
                v-for="(item, index) in provinceAreaOptions"
                :key="index"
                :label="item.text"
                :value="item.id">
              </el-option>
            </el-select>

          </el-col>
        </el-row>

        <el-row class="search-bar">
          <el-col :span="5" >
            <el-select size="small" v-model="search.courseId" clearable placeholder="请选择课程">
              <el-option
                v-for="item in courseOptions"
                :key="item.id"
                :label="item.courseName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="5" :offset="1">
            <el-select size="small" v-model="search.teacherId" clearable placeholder="请选择教练">
              <el-option
                v-for="item in coachOptions"
                :key="item.id"
                :label="item.teacherName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>

          <el-col :span="5" :offset="1">
            <el-select size="small" no-data-text='该地区，无相关校区' v-model="search.schoolId" clearable placeholder="请选择上课地点">
              <el-option
                v-for="item in schoolOptions"
                :key="item.schoolName"
                :label="item.schoolName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>

          <el-col :span="4" :offset="3">
            <el-button type="primary-plain" size="small" @click="getScheduleList()">搜索</el-button>
          </el-col>
        </el-row>

      </el-form>
      <!--
      <el-row>
        <el-col :span="3">
          <label>上课时间：</label>
        </el-col>
        <el-checkbox-group v-model="classTime">
          <el-checkbox v-for="time in timeList" :label="time.label" :key="time"></el-checkbox>
        </el-checkbox-group>
      </el-row>
      -->

      <div class="clearfix search-bar" >
        <span class="total">共<i class="class-total">{{lessonCount}}</i>节课</span>
      </div>
      <div v-if="classList.length" class="course-schedule">
        <div class="clearfix">
          <div class="fl" style="width:48px;">
            <ul class="hour">
              <li class="hour-item" style="line-height:51px;">{{theday.getMonth()+1}}月</li>
              <li v-for="(h,index) in hourList" class="hour-item" :key="index">
                {{new Date(h).format('hh:mm')}}
              </li>
            </ul>
          </div>
          <div class="fl" style="width:788px;">
            <table class="week-table">
              <tr>
                <td v-bind:style="{width:(100/7)+ '%'}" 
                  class="week week-day table-item" v-for="w in weekList" :key="w">
                  {{w}}
                </td>
              </tr>
              <tr>
                <td v-bind:style="{width:(100/7)+ '%'}" class="week table-item date-item" 
                  v-for="w in week" :key="w"
                  v-bind:class="{curMonth: theday.getMonth() == new Date(w).getMonth() }">
                  {{new Date(w).format('dd')}}
                </td>
              </tr>
            </table>

            <div class="course-table">
              <ul v-for="(item,index) in classList" class="course-line" :key="item.time"
                v-bind:class="{ odd: (index%2) == 1}">
                <li class="course-item" 
                  v-bind:style="{width:(100/7)+ '%'}"
                  v-for="(day,$index) in item.weekList"
                  :key="day.weekCode">
                  <div v-if="day.courseList.length" @click="showDetails($event, day.courseList, $index)">
                    <p class="hidden">{{day.courseList[0].courseName + '(' + day.courseList[0].classesName + ')' + day.courseList[0].subjectName}}</p>
                    <p class="hidden">{{ day.courseList[0].teacherName + ' ' }} <span v-if="day.courseList[0].scheduleType==1">改期</span><span v-if="day.courseList[0].scheduleType==2">代课</span> {{new Date(day.courseList[0].startTime).format('hh:mm') + ' - ' + new Date(day.courseList[0].endTime).format('hh:mm')}}</p>
                    <p>{{ day.courseList[0].schoolName + day.courseList[0].address}}</p>
                    <div v-if="day.courseList.length > 1" class="triangle"></div>
                  </div>                
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <e-placeholder v-else src="/static/images/no-course.png" text="当前还没有课程表哦！"/>

      <div class="ab" v-bind:style="{left: point.x +'px',top: point.y +'px'}" v-show="popVisible">
        <div class="popover right lesson-list">
          <i class="el-icon-close icon-close" @click="popVisible=false"></i>
          <div class="day">{{selectDate+ ' ' + selectWeekDay}} </div>
          <div v-for="(item,index) in courseList" :key="index" class="lesson">
            <p>{{item.courseName + '(' +item.classesName +')-' + item.subjectName }}</p>
            <p>{{item.teacherName}}<span v-if="item.scheduleType==1" class="red">(改期)</span><span v-if="item.scheduleType==2" class="red">(代课)</span>{{' ' +new Date(item.startTime).format('hh:mm') + ' - ' + new Date(item.endTime).format('hh:mm')}} </p>
            <p>{{item.schoolName + ' ' + item.address}}</p>
          </div>
        </div>
        <div class="arrow"></div>
        
      </div>    

    </div>
  </div>
</template>
<script>
import Api from 'api/train'
import {addDate, getMonthWeek, isIE} from 'utils'
import {mapGetters} from 'vuex'
export default {
  computed: {
    ...mapGetters({
      train_compus_selection: 'train_compus_selection'
    }),
    provinceAreaOptions () {
      if (this.train_compus_selection && this.train_compus_selection.length > 0) {
        let arr = this.train_compus_selection
        let result = []
        for (let item of arr) {
          let mid = {
            // id: `${item.provinceId}${item.cityId}`,
            // value: [item.provinceId, item.cityId],
            // text: `${item.provinceName}-${item.cityName}`
            id: [item.provinceId, item.cityId],
            text: `${item.provinceName}-${item.cityName}`
          }
          result.push(mid)
        }
        return result
      }
    },
    lessonCount () {
      let n = 0
      this.classList.forEach(c => {
        let w = c.weekList
        w.forEach(d => {
          if (d.courseList.length) {
            let cList = d.courseList
            cList.forEach(item => {
              n++
            })
          }
        })
      })
      return n
    },
    monthNumber () {
      let day = new Date(this.theday)
      return getMonthWeek(day.getFullYear(), day.getMonth(), day.getDate())
    },
    beginTime () {
      let IE = isIE()
      return IE ? +new Date(this.week[0]) : +new Date(this.week[0] + ' 00:00')
    },
    endTime () {
      let IE = isIE()
      return IE ? +new Date(this.week[6]) : +new Date(this.week[6] + ' 00:00')
    }
  },
  watch: {
    'theday': 'fillWeek',
    address (newVal) {
      if (newVal) {
        this.search.provinceId = newVal[0]
        this.search.cityId = newVal[1]
        this.getSchoolListByProCity()
      } else {
        this.search.provinceId = ''
        this.search.cityId = ''
        this.getSchoolListByProCity()
      }
    }
  },
  mounted () {
    this.handleChange()
    this.getScheduleList()
    this.fillHour()
    this.getOptions()
    this.$store.dispatch('train_compus_selection')
  },
  data () {
    return {
      address: '',
      selectDate: new Date(),
      selectWeekDay: '',
      popVisible: false,
      point: {
        x: 100,
        y: 100
      },
      courseList: [],
      classTime: [],
      total: 0,
      theday: new Date(),
      week: [],
      search: {
        provinceId: '',
        cityId: '',
        courseId: '',
        teacherId: '',
        schoolId: ''
        // province: '',
        // city: ''
      },
      coachOptions: [],
      schoolOptions: [],
      courseOptions: [],
      weekList: [
        '周日',
        '周一',
        '周二',
        '周三',
        '周四',
        '周五',
        '周六'
      ],
      timeList: [
        {
          value: 0,
          label: '上午（08:00-12:00）'
        },
        {
          value: 1,
          label: '下午（12:01-18:00）'
        },
        {
          value: 2,
          label: '晚上（18:01-22:00）'
        }
      ],
      hourList: [],
      classList: [],
      list: []
    }
  },
  methods: {
    handleChange (w) {
      this.week = []
      if (!this.theday) { // undefined
        this.theday = new Date()
      }
      let wd = new Date(this.theday).getDay()
      if (wd !== 1) {
        this.theday = new Date(addDate(new Date(), 1 - wd))
      }
      var wday = new Date(this.theday.getFullYear(), this.theday.getMonth(), this.theday.getDate(), 0, 0)
      for (var i = 0, l = 7; i < l; i++) {
        this.week.push(addDate(wday, i - 1))
      }
    },
    fillWeek () {
      this.week = []
      if (!this.theday) { // undefined
        this.theday = new Date()
      }
      let wd = new Date(this.theday).getDay()
      if (wd !== 1) {
        this.theday = new Date(addDate(new Date(), 1 - wd))
      }
      var wday = new Date(this.theday.getFullYear(), this.theday.getMonth(), this.theday.getDate(), 0, 0)
      for (var i = 0, l = 7; i < l; i++) {
        this.week.push(addDate(wday, i - 1))
      }
    },
    fillHour () {
      let year = new Date().getFullYear()
      for (let h = 8; h < 23; h++) {
        this.hourList.push(new Date(year, 1, 1, h, 0))
      }
    },
    getOptions () {
      Api.getScheduleOptions({}).then((res) => {
        let rdata = res.data
        if (rdata.trainCourseSimples.length) {
          this.courseOptions = rdata.trainCourseSimples
        }
        // 初始化校区选项（上课地点）
        if (rdata.trainSchoolSimples.length) {
          this.schoolOptions = rdata.trainSchoolSimples
        }
        if (rdata.trainTeacherSimples.length) {
          this.coachOptions = rdata.trainTeacherSimples
        }
      })
    },
    // 根据省市-更新-校区选项
    getSchoolListByProCity () {
      Api.getSchoolListByProCity({
        provinceId: this.search.provinceId,
        cityId: this.search.cityId
      }).then((res) => {
        if (Number(res.result) === 0) {
          this.schoolOptions = res.data
          for (let item of this.schoolOptions) {
            if (item.id === this.search.schoolId) {
              return
            }
          }
          this.search.schoolId = ''
        }
      })
    },
    // 隐藏弹框，并清空数据
    resetPopoverData () {
      this.popVisible = false
      this.courseList = []
    },
    getScheduleList () {
      Api.getScheduleList({
        provinceId: this.search.provinceId,
        cityId: this.search.cityId,
        schoolId: this.search.schoolId,
        teacherId: this.search.teacherId,
        courseId: this.search.courseId,
        orgUserId: localStorage.getItem('auth_orgId') || '',
        beginTime: this.beginTime,
        endTime: this.endTime
      }).then((res) => {
        this.classList = []
        for (let i = 0, l = res.data.length; i < l; i++) {
          let hour = res.data[i]
          let course = hour.weekList.pop()
          let courseList = [course]
          let wlist = courseList.concat(hour.weekList)
          this.classList.push({
            time: hour.time,
            weekList: wlist
          })
        }
        // this.classList = res.data
        this.resetPopoverData()
      })
    },
    showDetails (ev, course, index) {
      this.popVisible = true
      let day = new Date(this.week[index])
      this.selectDate = `${day.getMonth() + 1}月${day.getDate()}日`
      this.selectWeekDay = this.weekList[index]
      ev.stopPropagation()
      this.point.x = ev.pageX + 11 || ev.clientX // - ev.offsetX
      this.point.y = ev.pageY - 24 || ev.clientY // - ev.offsetY
      this.courseList = course
    },
    addDay (days) {
      this.theday = addDate(this.theday, days)
    }
  }
}
</script>

<style lang="scss" scoped>

$table-border-color:$color-divider;
.search-bar{
  margin:20px 0;
}
.total {
  font-size:20px;
  .class-total{
    font-style:normal;
    color: $color-primary;
  }
}
.hour-item{
  line-height:100px;
  border: 1px solid $table-border-color;
  text-align: center;
  border-bottom: 0;
}
.hour li:last-child{
  border-bottom: 1px solid $table-border-color;
}
.week-table,.course-table{
  width:100%;
  border-collapse:collapse;
  border-spacing: 0;
}
.week-table tr td{
  background: #fafafa;
}
.week{ 
  float:left;
  line-height:25px;
  text-align:center;
  border-collapse:collapse;
}
.week-day{
  border-bottom:0;
}
.course{
  height:100px;
  overflow: hidden;
  overflow-y: hidden;
  line-height: 15px;
  display: inline-block;
}
.table-item {
  border: 1px solid $table-border-color;
  border-left: 0;
  border-bottom: 0;
}
.course-table .course-line:last-child .course-item{
  height: 102px;
  border-bottom: 1px solid $table-border-color;
}
.course-item{
  border: 1px solid $table-border-color;
  height: 101px;
  float:left;
  border-left: 0;
  border-bottom: 0;
  overflow: hidden;
  line-height: 18px;
  position:relative;
  cursor: pointer;
  padding: 5px;
  font-size: 12px;
  color:#333;
}
.odd {
  .course-item{
    background: #fafafa;
  }
}
.triangle{
  width: 0;
  height: 0;
  border-top: 15px solid #01a87c;
  border-right: 15px solid transparent;
  border-left: 15px solid transparent;
  position: absolute;
  right: -15px;
  bottom: -3px;
  transform: rotate(-45deg);
}
.no-data{
  padding-top: 50px;
  p{
    margin:20px 0;
  }
}

.date-item{
  color:#999;
  &.curMonth{
    color:#333;
  }
}

.popover{
  position: relative;
  display: block;
  background-clip:padding-box;
  background-color:#fff;
  z-index: 2007;
  min-height: 222px;
  white-space:normal;
  width: 248px;
  border:1px solid #c2c2c2;
  padding: 10px;
  text-align: center;
  text-shadow: none;
  text-transform: none;
  border-radius: 2px;
  line-break:auto;
  webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);
  box-shadow: 0 5px 10px rgba(0,0,0,.2);
  .arrow{
    border-width:11px;    
    position: absolute;
    display: block;
    width: 0;
    height: 0;
    border-color:transparent;
    border-style: solid;
    &:after{
      position: absolute;
      display: block;
      width: 0;
      height: 0;
      border-color:transparent;
      border-style: solid;
      border-width: 10px;
      content: "";
    }
  }
  &.right{
    .arrow {
      top: 24px;
      left: -11px;
      margin-top: -11px;      
      border-right-color: #999; // IE8 fallback
      border-right-color: rgba(0,0,0,.25);
      border-left-width: 0;
      &:after {
        content: " ";
        left: 1px;
        bottom: -10px;
        border-left-width: 0;
        border-right-color: #fff;
        border-color:transparent;
        border-style: solid;
        box-sizing: border-box;
        border-right-color:#fff;
      }
    }
    .icon-close{
      position: absolute;
      right:10px;
      top:10px;
      cursor: pointer;
    }
  }
  .title{
    font-size: 16px;
    color: #333;
    font-weight: 700;
  }
  .tag{
    width: 16px;
    height: 16px;
    border-radius: 2px;
    background: #35dcaa;
    line-height: 16px;
    color: #fff;
    display: inline-block;
  }
 }
 .lesson-list{
    text-align: left;
    padding-top: 30px;
    .day{
      margin-bottom: 20px;
    }
    .lesson{
      margin-bottom: 20px;
    }
    p{
      line-height: 20px;
      font-size: 12px;
      color: #333;
    }
  }
  .red {
    color: #f60101;
  }

</style>
